from django.shortcuts import render, get_object_or_404, redirect
from django.core.paginator import Paginator
from django.db.models import Q
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .models import Bicycle, ViolationRecord
from .forms import BicycleForm

def bike_list(request):
    """自行车列表页面"""
    # 获取查询参数
    search = request.GET.get('search', '')
    category = request.GET.get('category', '')
    college = request.GET.get('college', '')
    
    # 构建查询
    bikes = Bicycle.objects.all()
    
    if search:
        bikes = bikes.filter(
            Q(bike_number__icontains=search) |
            Q(owner_name__icontains=search) |
            Q(owner_student_id__icontains=search) |
            Q(model__icontains=search) |
            Q(class_name__icontains=search)
        )
    
    if category:
        bikes = bikes.filter(category=category)
    
    if college:
        bikes = bikes.filter(college=college)
    
    # 分页
    paginator = Paginator(bikes, 10)  # 每页显示10条
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    # 获取选择项用于筛选器
    categories = Bicycle.CATEGORY_CHOICES
    colleges = Bicycle.COLLEGE_CHOICES
    
    context = {
        'page_obj': page_obj,
        'search': search,
        'category': category,
        'college': college,
        'categories': categories,
        'colleges': colleges,
        'total_count': bikes.count(),
    }
    
    return render(request, 'bike/bike_list.html', context)

def bike_detail(request, bike_id):
    """自行车详情页面"""
    bike = get_object_or_404(Bicycle, id=bike_id)
    
    # 获取该自行车的违章记录
    violations = bike.violations.all().order_by('-created_at')
    
    context = {
        'bike': bike,
        'violations': violations,
    }
    
    return render(request, 'bike/bike_detail.html', context)

def bike_statistics(request):
    """自行车统计页面"""
    # 按类别统计
    category_stats = {}
    for choice in Bicycle.CATEGORY_CHOICES:
        count = Bicycle.objects.filter(category=choice[0]).count()
        category_stats[choice[1]] = count
    
    # 按学院统计
    college_stats = {}
    for choice in Bicycle.COLLEGE_CHOICES:
        count = Bicycle.objects.filter(college=choice[0]).count()
        college_stats[choice[1]] = count
    
    # 总数统计
    total_bikes = Bicycle.objects.count()
    total_violations = ViolationRecord.objects.count()
    
    # 违章统计
    violation_stats = {
        'total': total_violations,
        'pending': ViolationRecord.objects.filter(status='pending').count(),
        'processing': ViolationRecord.objects.filter(status='processing').count(),
        'resolved': ViolationRecord.objects.filter(status='resolved').count(),
        'dismissed': ViolationRecord.objects.filter(status='dismissed').count(),
    }
    
    # 按学院统计违章已处理数量
    college_violation_stats = []
    for choice in Bicycle.COLLEGE_CHOICES:
        college_code = choice[0]
        college_name = choice[1]
        # 统计该学院已处理的违章数量（resolved + dismissed）
        resolved_count = ViolationRecord.objects.filter(
            bicycle__college=college_code, 
            status='resolved'
        ).count()
        dismissed_count = ViolationRecord.objects.filter(
            bicycle__college=college_code, 
            status='dismissed'
        ).count()
        college_violation_stats.append({
            'college': college_name,
            'processed_count': resolved_count + dismissed_count
        })
    
    # 检查用户权限
    user_permissions = {
        'is_authenticated': request.user.is_authenticated,
        'is_admin': False,
        'is_super_admin': False,
        'college': None
    }
    
    if request.user.is_authenticated:
        try:
            from .models import CollegeUser
            college_user = CollegeUser.objects.get(user=request.user)
            user_permissions['is_admin'] = college_user.is_admin
            user_permissions['is_super_admin'] = college_user.is_super_admin
            user_permissions['college'] = college_user.college
            user_permissions['college_display'] = college_user.get_college_display()
        except:
            pass
    
    context = {
        'category_stats': category_stats,
        'college_stats': college_stats,
        'total_bikes': total_bikes,
        'total_violations': total_violations,
        'violation_stats': violation_stats,
        'college_violation_stats': college_violation_stats,
        'user_permissions': user_permissions,
    }
    
    return render(request, 'bike/bike_statistics.html', context)

def violation_list(request):
    """前台违章车辆列表页面"""
    # 获取查询参数
    search = request.GET.get('search', '')
    violation_type = request.GET.get('violation_type', '')
    status = request.GET.get('status', '')
    college = request.GET.get('college', '')
    
    # 构建查询
    violations = ViolationRecord.objects.select_related('bicycle').all()
    
    if search:
        violations = violations.filter(
            Q(bicycle__bike_number__icontains=search) |
            Q(bicycle__owner_name__icontains=search) |
            Q(location__icontains=search) |
            Q(reporter_name__icontains=search)
        )
    
    if violation_type:
        violations = violations.filter(violation_type=violation_type)
    
    if status:
        violations = violations.filter(status=status)
    
    if college:
        violations = violations.filter(bicycle__college=college)
    
    # 按时间倒序排列
    violations = violations.order_by('-created_at')
    
    # 分页
    paginator = Paginator(violations, 15)  # 每页显示15条
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    # 获取选择项用于筛选器
    violation_types = ViolationRecord.VIOLATION_TYPES
    status_choices = ViolationRecord.STATUS_CHOICES
    colleges = Bicycle.COLLEGE_CHOICES
    
    # 统计信息
    total_violations = violations.count()
    pending_count = violations.filter(status='pending').count()
    processing_count = violations.filter(status='processing').count()
    resolved_count = violations.filter(status='resolved').count()
    dismissed_count = violations.filter(status='dismissed').count()
    
    context = {
        'page_obj': page_obj,
        'search': search,
        'violation_type': violation_type,
        'status': status,
        'college': college,
        'violation_types': violation_types,
        'status_choices': status_choices,
        'colleges': colleges,
        'total_violations': total_violations,
        'pending_count': pending_count,
        'processing_count': processing_count,
        'resolved_count': resolved_count,
        'dismissed_count': dismissed_count,
    }
    
    return render(request, 'bike/violation_list.html', context)




